<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="产品名称" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              :filter-method="hospitalFilter"
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
            >
              <el-option
                 v-for="item in supplierList"
                :key="item.id"
                :label="item.name + ' ' + item.standard"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品规格" min-width="80" v-if="false">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productStandards" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="生产批次" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productBatch`" class="mb-0px!">
            <el-select
              v-model="row.productBatch"
              clearable
              filterable
              @click="getProductBatchList(row)"
              @change="onChangeProductBatch($event, row)"
              placeholder="请选择批次"
            >
              <el-option
                    v-for="productBatchItem in row.productBatchList"
                    :key="productBatchItem"
                    :label="productBatchItem"
                    :value="productBatchItem"
                />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="入库批次" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inboundBatch`" class="mb-0px!">
            <el-select
              v-model="row.inboundBatch"
              clearable
              filterable
              @click="getInboundBatchList($event, row)"
              @change="onChangeInboundBatch($event, row)"
              placeholder="请选择批次"
            >
              <el-option
                    v-for="batchItem in row.inboundBatchList"
                    :key="batchItem"
                    :label="batchItem"
                    :value="batchItem"
                />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="有效期" min-width="180">
  <template #default="{ row }">
    <el-form-item class="mb-0px!">
      <el-date-picker type="datetime" disabled v-model="row.productValidityDate" />
    </el-form-item>
  </template>
</el-table-column>
      <el-table-column label="账面库存" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.stockCount" :formatter="erpCountInputFormatter2" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productUnitName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="实际库存" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.actualCount`"
            :rules="formRules.actualCount"
            class="mb-0px!"
          >
            <el-input-number
              v-model="row.actualCount"
              controls-position="right"
              :precision="0"
              :step="1"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="盈亏数量" prop="rowcount" min-width="110">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.rowcount`" :rules="formRules.rowcount" class="mb-0px!">
            <el-input
              disabled
              v-model="row.rowcount"
              :formatter="erpCountInputFormatter2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60" v-if="!disabled">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" style="margin-top: 10px; margin-bottom: 10px;" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加盘点产品</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { StockCheckApi } from '@/api/spd/hospitaloffice/stockcheck'
import { PriStockApi, PriStockVO } from '@/api/erp/pristock'
import debounce from 'lodash/debounce'
import { defaultProps, handleTree } from '@/utils/tree'
import { ProductApi, ProductVO } from '@/api/spd/product/product'
const supplierList = ref<ProductVO[]>([])  // 供应商列表

import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'

interface StockCheckItem {
  id: number | undefined;
  deptId: number | undefined;
  productStandards: string | undefined;
  productId: number | undefined;
  productName: string | undefined;
  addDelType: number | undefined;
  productUnitId: number | undefined;
  productUnitName: string | undefined;
  productBarCode: string | undefined;
  productPrice: number | undefined;
  stockCount: number | undefined;
  actualCount: number | undefined;
  rowcount: number | undefined;
  totalPrice: number | undefined;
  remark: string | undefined;
  productBatch: string | undefined;
  inboundBatch: string | undefined;
  productValidityDate: Date[] | undefined;
  productBatchList: string[] | undefined;
  inboundBatchList: string[] | undefined;
}

const props = defineProps<{
  items: undefined
  // items: []
  disabled: false
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<StockCheckItem[]>([])
// const formData = ref<[]>([])
const formRules = reactive({
  inId: [{ required: true, message: '盘点编号不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<PriStockVO[]>([]) // 产品列表

const erpCountInputFormatter2 = (val) => {
  return Math.round(val);
}

var deptId2: undefined
onMounted(() => {
  const Info = JSON.parse(localStorage.getItem('user') || '{}');
  const userInfo = JSON.parse(Info.v)
  deptId2 = userInfo.user.deptId
  
});

/**
 * 键入监听方法
 */
const hospitalFilter =async(params)=> {
  //判断键入是否有值
  if(params!==""){
    //有值调用防抖方法
    debouncedSearch(params)
  }else{
    const ids = await PriStockApi.getIds();
    const data = await ProductApi.getProductSimpleListByIds(params,ids)
    supplierList.value = data
  }
}

/**
 * 根据键入的值查询产品列表
 */
const productLists=async(params)=>{
  // 加载产品列表
  const ids = await PriStockApi.getIds();
  const supplierData = await ProductApi.getProductSimpleListByIds(params,ids)
  supplierList.value = handleTree(supplierData, 'id')
}

// 创建一个防抖函数来处理搜索操作
 const debouncedSearch =debounce((params,delay = 500) => { 
      //定义等待时间
      const timer = ref() 
      // 模拟异步数据获取（例如API调用）
      if(timer.value){
          //清除等待时间
          clearTimeout(timer.value); 
        }
      //等待时间赋值
      timer.value = setTimeout(async() => {
        //调用后端根据键入的值查询产品列表方法
        productLists(params)
      }, delay); // 延迟500毫秒以模拟网络延迟或数据处理时间
  }, 500); // 防抖等待时间为500毫秒   

/** 初始化设置盘点项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

// /** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      if (item.stockCount!= null && item.actualCount!= null) {
        item.rowcount = item.actualCount - item.stockCount
        // 根据count的值判断并设置addDelType
        if (item.rowcount > 0) {
          item.addDelType = 1;
        } else {
          item.addDelType = 0;
        }
      } else {
        item.rowcount = undefined
        item.addDelType = undefined;
      }
      item.totalPrice = erpPriceMultiply(item.productPrice, item.rowcount)
    })
  },
  { deep: true }
)

/** 检查 productId 和 productBatch 组合是否重复 */
const isCombinationDuplicate = (productId, productBatch,currentRow?: StockCheckItem) => {
  return formData.value.some(item => 
    item!== currentRow && item.productId === productId && item.productBatch === productBatch
  );
};


/** 新增按钮操作 */
const handleAdd = () => {
 const row = {
    id: undefined,
    deptId: deptId2,
    productStandards: undefined,
    productId: undefined,
    productName: undefined, // 产品名称
    addDelType: undefined,
    productUnitId: undefined, // 产品单位
    productUnitName: undefined, // 产品单位
    productBarCode: undefined, // 产品条码
    productPrice: undefined,
    stockCount: undefined,
    actualCount: undefined,
    rowcount: undefined,
    totalPrice: undefined,
    remark: undefined,
    productBatch: undefined,
    inboundBatch: undefined,
    productValidityDate: [],
    inboundBatchList: [],
    productBatchList: []
  };
  formData.value.push(row)
}


/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 处理仓库变更 */
// const onChangeWarehouse = (deptId, row) => {
//   // 加载库存
//   setStockCount(row)
// }

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
    const product = productList.value.find((item) => item.productId == productId);
    row.productBatch = undefined
    row.inboundBatch = undefined
    row.productStandards = undefined
    row.repertoryCount = undefined
    row.productUnitId = undefined
    row.productValidityDate = undefined
    row.productUnitName = undefined
    row.productPrice = undefined
    row.count = undefined
    row.stockCount = undefined
    row.actualCount = undefined
    row.rowcount = undefined
    row.addDelType = undefined
    row.totalPrice = undefined
    if (product) {
        const productBatchList =  setProductBatchList(product.productId,row);
        row.productBatchList = productBatchList;
        if (productBatchList && productBatchList.length > 0) {
            // 设置初始批次，这里选择第一个批次，可根据实际需求调整
            row.productBatch = productBatchList[0];
        }
        row.productStandards = product.productStandards;   
    }
};


const onChangeProductBatch = (productBatch, row) => {
  if (isCombinationDuplicate(row.productId, row.productBatch, row)) {
    ElMessage.warning('该产品和批次组合已存在，请重新选择！');
    row.productBatch = undefined; // 清空选择
    return;
  }
  const product = productList.value.find((item) => item.productId == row.productId && item.productBatch == productBatch);
    row.productStandards = undefined
    row.repertoryCount = undefined
    row.productUnitId = undefined
    row.productValidityDate = undefined
    row.productUnitName = undefined
    row.productPrice = undefined
    row.count = undefined
    row.stockCount = undefined
    row.actualCount = undefined
    row.rowcount = undefined
    row.addDelType = undefined
    row.totalPrice = undefined
  if (product) {
    row.productId = product.productId
    row.productName = product.productName
    row.productUnitId = product.productUnitId
    row.productUnitName = product.productUnitName
    row.productStandards = product.productStandards;   
    row.productValidityDate = product.productValidityDate
    row.productBatch = product.productBatch
    row.actualCount = product.count
    row.stockCount = product.count
    row.count = product.count
    // 加载库存
  setStockCount(row)
  }
};

// const onChangeInboundBatch = (inboundBatch, row) => {
//   if (isCombinationDuplicate(row.productId, row.productBatch, inboundBatch, row)) {
//     ElMessage.warning('该产品和批次组合已存在，请重新选择！');
//     row.productBatch = undefined; // 清空选择
//     row.inboundBatch = undefined; // 清空选择
//     return;
//   }
//     row.productStandards = undefined
//     row.repertoryCount = undefined
//     row.productUnitId = undefined
//     row.productValidityDate = undefined
//     row.productUnitName = undefined
//     row.productPrice = undefined
//     row.count = undefined
//     row.stockCount = undefined
//     row.actualCount = undefined
//     row.rowcount = undefined
//     row.addDelType = undefined
//     row.totalPrice = undefined
//   const product = productList.value.find((item) => item.productId == row.productId && item.productBatch == row.productBatch && item.inboundBatch == inboundBatch);
//   if (product) {
//     row.productId = product.productId
//     row.productName = product.productName
//     row.productUnitId = product.productUnitId
//     row.productUnitName = product.productUnitName
//     row.productStandards = product.productStandards;   
//     row.productValidityDate = product.productValidityDate
//     row.productBatch = product.productBatch
//     row.actualCount = product.count
//     row.stockCount = product.count
//     row.count = product.count
//     // 加载库存
//   setStockCount(row)
//   }
  
// };

const getProductBatchList = (row) => {
  const product = productList.value.find((item) => item.productId == row.productId);
  if (product) {
        const batchList =  setProductBatchList(row.productId,row);
        row.productName = product.productName;
        row.productBatchList = batchList;
        if (batchList && batchList.length > 0) {
            // 设置初始批次，这里选择第一个批次，可根据实际需求调整
            row.productBatch = batchList[0];
        }
    }
};

// const getInboundBatchList = (productBatch, row) => {
//   const product = productList.value.find((item) => item.productId == row.productId && item.productBatch == productBatch);
//   if (product) {
//         const batchList =  setInboundBatchList(row.productId,productBatch,row);
//         row.inboundBatchList = batchList;
//         if (batchList && batchList.length > 0) {
//             // 设置初始批次，这里选择第一个批次，可根据实际需求调整
//             row.inboundBatch = batchList[0];
//         }
//     }
// };

/** 加载库存 */
const setStockCount = async (row) => {
    if (!row.productId || !row.deptId) {
        return;
    }
    const stock = await PriStockApi.getProductByBatch(row.productId, row.productBatch);
    row.stockCount = stock.count
    row.actualCount = stock.count
    row.productUnitId = stock.productUnitId
    row.productUnitName = stock.productUnitName
    row.productValidityDate = stock.productValidityDate
    row.productBatch = stock.productBatch
    row.productName = stock.productName
    row.productStandards = stock.productStandards
};

const setProductBatchList = async (productId,row) => {
    if (!productId) {
        return [];
    }
    try {
        const batchList = await PriStockApi.getProductBatchsByProductId(productId);
        row.productBatchList = batchList;
        return batchList;
    } catch (error) {
        return [];
    }
};

// const setInboundBatchList = async (productId,productBatch,row) => {
//     if (!productId) {
//         return [];
//     }
//     try {
//         const batchList = await PriStockApi.getInboundBatchsByProductId(productId,productBatch);
//         row.inboundBatchList = batchList;
//         return batchList;
//     } catch (error) {
//         return [];
//     }
// };

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({ validate })

/** 初始化 */
onMounted(async () => {
  const ids = await PriStockApi.getIds();
  const data1 = await ProductApi.getProductSimpleListByIds('',ids)
  supplierList.value = data1
  const data2 = await PriStockApi.getPriStockListByBatch();
  productList.value = data2
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})

</script>
